package com.c2soft.ncmxBtrade.webApp;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
//import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SecurityInitializer extends
		AbstractSecurityWebApplicationInitializer {


	public SecurityInitializer() {
		super(WebSecurityConfig.class);
	}

	@Configuration
	@EnableWebMvcSecurity
	@Import({ DataSourceConfig.class })
	public static class WebSecurityConfig extends WebSecurityConfigurerAdapter {

		@Autowired
		private AuthenticationSuccessHandler successHandler;
		
		
		@Override
		public void configure(WebSecurity web) throws Exception {
			web.ignoring().antMatchers("/resources/**");

		}

		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.csrf().disable();

			http.authorizeRequests()
					.antMatchers("/", "/index**","/forgotPwd**","/tradeBook","/headWebSocket","/user/ForgetPwd/**")
					.permitAll()
					.antMatchers("/css/**", "/img/**", "/image/**", "/js/**",
							"/j_spring_security_check").permitAll()
					.antMatchers("/**", "/index**").hasRole("BROKER")
					.anyRequest()
					.authenticated().and().formLogin().loginPage("/login")
					.successHandler( successHandler)
					.permitAll().and().logout().logoutUrl("/logout")
					.logoutSuccessUrl("/login").permitAll();

		}

		@Autowired
		public void configureGlobal(DataSource dataSource,AuthenticationManagerBuilder auth)
				throws Exception {
			auth.jdbcAuthentication()
					.dataSource(dataSource)
					.usersByUsernameQuery(
							"select fname,password, enabled from users where user_id=?")
					.authoritiesByUsernameQuery(
							" select u.fname, ur.authority from users u, user_roles ur where u.user_id = ur.user_id and u.fname =?");
		}

	}
}
